package com.ideafactory.client.utils.commonexception;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.ideafactory.client.ybservice.APP;
import com.ideafactory.client.ybservice.AppActivityManager;

import java.lang.Thread.UncaughtExceptionHandler;

// 创建服务用于捕获崩溃异常  
public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
	APP app = null;
	private PendingIntent restartIntent;
	public static String ERROR_FILE_SAVE_PATH = Environment.getExternalStorageDirectory() + "/Hsd_Error/";

	public MyUncaughtExceptionHandler(APP app) {
		this.app = app;
		Intent intent = new Intent();
		String packgeName = app.getPackageName();
		// 参数1：包名，参数2：程序入口的activity
		intent.setClassName(packgeName, "com.ideafactory.client.ybservice.YbSelfService");

		Log.e("APP", "packgeName------------> "+packgeName+".YbSelfService" );
		restartIntent = PendingIntent.getActivity(app.getApplicationContext(), 123456, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// 1秒钟后重启应用
		AlarmManager mgr = (AlarmManager) app.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 300, restartIntent);
		AppActivityManager.getAppActivityManager().finishAllActivity();
		finishProgram();
	}

	// 结束线程,一般与finishAllActivity()一起使用
	// 例如: finishAllActivity;finishProgram();
	public void finishProgram() {
		android.os.Process.killProcess(android.os.Process.myPid());
	}


}
